// Bot Manager for Peril Dice
// Handles logic for test players (bots): picking numbers and rolling dice

// Configuration
integer LISTEN_CHANNEL = -9999; // Change if needed to match main controller

// Helper to parse and respond to pick commands
doBotPick(string botName, integer count, integer diceMax) {
    list picks;
    while (llGetListLength(picks) < count) {
        integer roll = 1 + (integer)(llFrand((float)diceMax));
        if (llListFindList(picks, [roll]) == -1) {
            picks += roll;
        }
    }
    string pickString = llDumpList2String(picks, ",");
    llRegionSay(LISTEN_CHANNEL, "BOT_PICKED:" + botName + ":" + pickString);
}

// Helper to respond to peril roll commands
doBotRoll(string botName, integer diceMax) {
    integer roll = 1 + (integer)(llFrand((float)diceMax));
    llRegionSay(LISTEN_CHANNEL, "BOT_ROLL:" + botName + ":" + (string)roll);
}

default {
    state_entry() {
        llListen(LISTEN_CHANNEL, "", NULL_KEY, "");
        llOwnerSay("[Bot Manager] Ready and listening on channel " + (string)LISTEN_CHANNEL);
    }

    listen(integer channel, string name, key id, string message) {
        if (llSubStringIndex(message, "BOT_PICK:") == 0) {
            // Format: BOT_PICK:bot_1:3:20
            list parts = llParseStringKeepNulls(message, [":"], []);
            if (llGetListLength(parts) == 4) {
                string botName = llList2String(parts, 1);
                integer count = (integer)llList2String(parts, 2);
                integer diceMax = (integer)llList2String(parts, 3);
                doBotPick(botName, count, diceMax);
            }
        }
        else if (llSubStringIndex(message, "BOT_PERIL_ROLL:") == 0) {
            // Format: BOT_PERIL_ROLL:bot_1:20
            list parts = llParseStringKeepNulls(message, [":"], []);
            if (llGetListLength(parts) == 3) {
                string botName = llList2String(parts, 1);
                integer diceMax = (integer)llList2String(parts, 2);
                doBotRoll(botName, diceMax);
            }
        }
    }
}
